<template>
  <div>
    <!-- 营养商品 -->
    <h1>营养餐品</h1>
    <el-form :inline="true">
      <el-form-item label="">
        <el-input v-model="searchForm.shopName" placeholder="请输入餐厅名称">
        </el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入餐品名称"
        ></el-input>
      </el-form-item>
      <el-button class="search" type="success" @click="getList()"
        >查询商品</el-button
      >
    </el-form>
    <el-table
      ref="multipleTable"
      tooltip-effect="drak"
      style="width: 100%"
      :data="list"
    >
      <el-table-column label="餐厅名称" prop="shopName" width="160">
      </el-table-column>
      <el-table-column
        label="餐品名称"
        prop="name"
        width="100"
      ></el-table-column>
      <el-table-column label="商品图片">
        <template slot-scope="scope">
          <img
            style="width: 80px; height: 80px; border: none"
            :src="'http://localhost:8081/' + scope.row.img"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="餐品描述"
        prop="description"
        width="300"
      ></el-table-column>
      <el-table-column
        label="价格/元"
        prop="money"
        width="100"
      ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="addCar(scope.row.id)"
            >加入购物车</el-button
          >
          <el-button
            type="success"
            size="mini"
            @click="buyGoods(scope.row.id, scope.row.name, scope.row.money)"
            >购买商品</el-button
          >
          <el-button size="mini" @click="getGoods(scope.row.id)" width="100"
            >查看详细</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 查询商品详细页面 -->
    <el-dialog
      title="餐品详细页面"
      :visible.sync="searchInfo"
      width="80%"
      :before-close="handleClose"
      class="search_dialog"
    >
      <div class="container">
        <h3>商店详细——{{ goods.shopName }}——{{ goods.name }}</h3>
        <el-carousel height="400ppx'" type="card">
          <el-carousel-item>
            <img
              :src="'http://localhost:8081/' + goods.img"
              alt="暂无图片"
              title="商品图片"
            />
          </el-carousel-item>
          <el-carousel-item>
            <img
              :src="'http://localhost:8081/' + goods.breakfastimg"
              alt="暂无图片"
              title="商品早餐"
            />
          </el-carousel-item>
          <el-carousel-item>
            <img
              :src="'http://localhost:8081/' + goods.lunchimg"
              alt="暂无图片"
              title="商品午餐"
            />
          </el-carousel-item>
          <el-carousel-item>
            <img
              :src="'http://localhost:8081/' + goods.dinnerimg"
              alt="暂无图片"
              title="商品晚餐"
            />
          </el-carousel-item>
        </el-carousel>
        <el-descriptions :column="2">
          <el-descriptions-item label="商品名称">{{
            goods.name
          }}</el-descriptions-item>
          <el-descriptions-item label="商店名称">{{
            goods.shopName
          }}</el-descriptions-item>
          <el-descriptions-item label="营养早餐">{{
            goods.breakfast
          }}</el-descriptions-item>
          <el-descriptions-item label="营养午餐">{{
            goods.lunch
          }}</el-descriptions-item>
          <el-descriptions-item label="营养晚饭">{{
            goods.dinner
          }}</el-descriptions-item>
          <el-descriptions-item label="商店介绍">{{
            goods.shopDescription
          }}</el-descriptions-item>
          <el-descriptions-item label="商品介绍">{{
            goods.description
          }}</el-descriptions-item>
        </el-descriptions>
         <div class="btn-container">
          <el-button type="danger" @click="searchInfo = false">关闭</el-button>
          <el-button type="primary"  @click="addCar(goods.id)"
              >加入购物车</el-button>
            <el-button
              type="success"
              @click="buyGoods(goods.id, goods.name, goods.money)"
              >购买商品</el-button>
         </div>
        <j-comment
          :title="'商品-' + goods.name + '评论'"
          :key-map="keyMap"
          :showNumber="2"
          :comment-datas="commentDatas"
          @submitComment="submitComment"
        >
        </j-comment>
        <div v-if="commentDatas.length == 0" class="remark">暂无评论</div>
      </div>
    
      
    </el-dialog>

    <!-- 商品购物清单 -->
    <el-dialog
      title="商品购物清单"
      :visible.sync="buyInfo"
      width="80"
      :before-close="close"
    >
      <el-form :model="info" :rules="infoRules" ref="info" label-width="100px">
        <el-form-item label="购物数量" prop="num">
          <el-input v-model="info.num"></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="info.address"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="confirm()">确定</el-button>
      <el-button type="danger" @click="buyInfo = false">关闭</el-button>
    </el-dialog>

    <el-dialog
      title="商品支付界面"
      :visible.sync="payInfo"
      width="80"
      :before-close="close"
    >
      <div class="font">
        您确定购买 {{ info.name }} 商品 , 购买数量为{{ info.num }}, 送货地址为{{
          info.address
        }}
        吗？ 单件商品的价格为{{ info.price }} 元 , 共计
        {{ parseInt(info.num) * parseInt(info.price) }}元
      </div>
      <el-button type="success" @click="buy">确定付款</el-button>
      <el-button type="danger" @click="payInfo = false">取消</el-button>
    </el-dialog>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="current"
      :page-size="size"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "Info",
  data() {
    const isNum = (rule, value, callback) => {
      const price = /^[0-9]*$/;
      if (!price.test(value)) {
        callback(new Error("金额只能为数字"));
        this.info["num"] = "";
      } else {
        callback();
      }
    };
    const isNum2 = (rule, value, callback) => {
      const num = /^[0-9]*$/;
      if (!num.test(value) || num > 0) {
        callback(new Error("数量必须大于0"));
        this.info["num"] = "";
      } else {
        callback();
      }
    };
    return {
      total: 0,
      size: 10,
      current: 1,
      list: [],
      addForm: false,
      payInfo: false,
      searchForm: {
        name: "",
        shopName: "",
      },
      keyMap: {
        pid: "pid",
        id: "id",
      },
      searchInfo: false,
      goods: {},
      formRules: {
        name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        shopName: [
          {
            required: true,
            message: "请输入商店名称",
            trigger: "blur",
          },
        ],
        breakfast: [
          {
            required: true,
            message: "请输入商品早餐",
            trigger: "blur",
          },
        ],
        lunch: [
          {
            required: true,
            message: "请输入商品午餐",
            trigger: "blur",
          },
        ],
        dinner: [
          {
            required: true,
            message: "请输入商品晚餐",
            trigger: "blur",
          },
        ],
        money: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
          {
            validator: isNum,
            message: "价格必须大于0",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入商品概要", trigger: "blur" },
        ],
      },
      commentDatas: [],
      info: {},
      buyInfo: false,
      infoRules: {
        num: [
          {
            required: true,
            message: "请输入购物数量",
            trigger: "blur",
          },
          {
            validator: isNum,
            message: "价格必须大于0",
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入收货地址",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    getList() {
      this.$axios
        .get("/sys/goods/list", {
          params: {
            name: this.searchForm.name,
            shopName: this.searchForm.shopName,
            current: this.current,
            size: this.size,
          },
        })
        .then((res) => {
          this.list = res.data.data.records;
          this.size = res.data.data.size;
          this.current = res.data.data.current;
          this.total = res.data.data.total;
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios
            .post(
              "/sys/goods/" + (this.goods.id ? "update" : "save"),
              this.goods
            )
            .then((res) => {
              this.getList();
              this.resetForm();
              this.$message({
                showClose: true,
                message: res.data.data,
                type: "success",
                onClose: () => {},
              });
            });
          this.addForm = false;
        }
      });
    },
    resetForm() {
      this.addForm = false;
      this.searchInfo = false;
      this.goods = {};
      this.commentDatas = [];
    },
    handleSizeChange(val) {
      this.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.current = val;
      this.getList();
    },
    handleClose() {
      this.resetForm();
    },
    editHandle(id) {
      this.$axios.get("/sys/goods/info/" + id).then((res) => {
        this.goods = res.data.data;
        this.addForm = true;
      });
    },
    seachInfoClose() {
      this.resetForm();
    },
    getGoods(id) {
      this.getComment(id);
      this.$axios.get("/sys/goods/info/" + id).then((res) => {
        this.goods = res.data.data;
        this.searchInfo = true;
      });
    },
    getComment(id) {
      this.$axios.get("/goods/comment/info/" + id).then((res) => {
        this.commentDatas = res.data.data;
        console.log(this.commentDatas);
      });
    },
    selectEmoji(emoji) {
      console.log(emoji);
    },
    /**
     * 表情转码
     * @param {string} str  需要转码的表情
     * @return {string} 转码后的字符串
     */
    utf16toEntities(str) {
      const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
      str = str.replace(patt, (char) => {
        let H, L, code, s;
        if (char.length === 2) {
          H = char.charCodeAt(0); // 取出高位
          L = char.charCodeAt(1); // 取出低位
          code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00; // 转换算法
          s = `&#${code};`;
        } else {
          s = char;
        }
        return s;
      });
      return str;
    },
    /**
     * 表情转码
     * @param {string} str  需要转码的表情
     * @return {string} 转码后的字符串
     */
    utf16toEntities(str) {
      const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
      str = str.replace(patt, (char) => {
        let H, L, code, s;
        if (char.length === 2) {
          H = char.charCodeAt(0); // 取出高位
          L = char.charCodeAt(1); // 取出低位
          code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00; // 转换算法
          s = `&#${code};`;
        } else {
          s = char;
        }
        return s;
      });
      return str;
    },

    submitComment(item) {
      item["goodId"] = this.goods.id;
      console.log("item: ", item);
      this.$axios.post("/goods/comment/save", item).then((res) => {
        this.getComment(this.goods.id);
        this.$message({
          showClose: true,
          message: res.data.data,
          type: "success",
          onClose: () => {},
        });
      });
    },
    delHandle(id) {
      this.$axios.get("/sys/goods/delete?id=" + id).then((res) => {
        this.getList();
        this.$message({
          showClose: true,
          message: res.data.data,
          type: "success",
          onClose: () => {},
        });
      });
    },
    addCar(id) {
      this.$confirm("确定是否加入购物车？", "商品信息", {
        confirmButtonText: "加入购物车",
        cancelButtonText: "取消",
        type: "success",
      }).then(() => {
        this.$axios.post("/goods/info/addCar", { goodsId: id }).then((res) => {
          this.$message({
            showClose: true,
            message: res.data.data,
            type: "success",
          });
        });
      });
    },
    buyGoods(id, name, money) {
      this.info = {};
      this.buyInfo = true;
      this.info["goodsId"] = id;
      this.info["name"] = name;
      this.info["price"] = money;
    },
    close() {
      this.buyInfo = false;
      this.payInfo = false;
    },
    buy() {
      this.$axios.post("/goods/info/addInfo", this.info).then((res) => {
        this.close();
        this.$message({
          showClose: true,
          message: res.data.data,
          type: "success",
        });
      });
    },
    confirm() {
      if (this.info["num"] == null || this.info["num"] == "") {
        this.$message({
          showClose: true,
          message: "购买数量",
          type: "error",
        });
        return;
      }
      if (this.info["address"] == null || this.info["address"] == "") {
        this.$message({
          showClose: true,
          message: "请输入收货地址",
          type: "error",
        });
        return;
      }
      this.buyInfo = false;
      this.payInfo = true;
    },
  },

  created() {
    console.log(this.$route.query.name);
    this.searchForm.shopName = this.$route.query.name;
    this.getList();
  },
};
</script>

<style scoped>
.container h3 {
  margin-left: 50%;
  transform: translateX(-25%);
  margin-top: -20px;
}
.search_dialog {
  margin-left: 10% !important;
}
.has-colon {
  font-weight: 600;
}
.remark {
  margin-left: 50%;
  transform: translateX(-25%);
  color: #ccc;
  font-size: 25px;
}
.el-table {
  font-size: 18px;
}
div /deep/.el-dialog__title {
  font-size: 22px;
}

.el-table,
div /deep/.el-form-item__label,
.el-input {
  font-size: 18px;
}

.font {
  font-size: 18px;
}
.el-carousel img {
  margin-left: 70px;
  width: 500px;
  height: 300px;
}
</style>